#include "mytcpserver.h"
#include <QThread>
#include <QTimer>
#include "mytcpsocket.h"
#include "mytcpsockettoall.h"

MyTcpServer::MyTcpServer(QObject *parent)
    : QTcpServer{parent}
    , autoFreeTimer(new QTimer)
{
    connect(autoFreeTimer, &QTimer::timeout,
            this, &MyTcpServer::autoFreeTimerTimeoutSlot);
    autoFreeTimer->start(5000);
}

void MyTcpServer::serverCloseAndClear()
{
    if(this->isListening())
        this->close();
    emit abortAllClient();
}

void MyTcpServer::socketDisconnectedSlot()
{
    MyTcpSocket *socket = qobject_cast<MyTcpSocket *>(sender());
    disconnect(socket, nullptr, nullptr, nullptr);
    disconnect(this, nullptr, socket, nullptr);
    socket->deleteLater();
    socket->thread()->exit();
}

void MyTcpServer::autoFreeTimerTimeoutSlot()
{
    autoFreeThread();
}

void MyTcpServer::incomingConnection(qintptr socketDescriptor)
{
    MyTcpSocketToAll *socket = new MyTcpSocketToAll;

    socket->setSocketDescriptor(socketDescriptor);

    connect(socket, &MyTcpSocket::disconnected,
            this, &MyTcpServer::socketDisconnectedSlot);
    connect(this, &MyTcpServer::abortAllClient,
            socket, &MyTcpSocket::myAbortSlot);

    connect(socket, &MyTcpSocketToAll::sendDataToIdentity,
            this, &MyTcpServer::sendDataToIdentity);
    connect(this, &MyTcpServer::sendDataToIdentity,
            socket, &MyTcpSocketToAll::sendDataToIdentitySlot);


    QThread *th = new QThread;
    th->start();
    socket->moveToThread(th);
    thList.append(th);
}

void MyTcpServer::autoFreeThread()
{
    for(int i = 0; i < thList.length(); i++)
    {
        if(thList.at(i)->isFinished())
        {
            QThread * th = thList.at(i);
            thList.removeAt(i);
            th->deleteLater();
            i--;
        }
    }
}
